package com.fdd.op.sdk.internal.util;

import com.fdd.op.sdk.constants.Constants;
import com.fdd.op.sdk.internal.util.json.JSONWriter;
import org.apache.commons.codec.digest.DigestUtils;

import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * @author opadmin
 */
public class SignatureUtils {

    private static void notNull(Object object, String message) {
        if (object == null) {
            throw new IllegalArgumentException(message);
        }
    }

    private static long getCurrentTimestamp() {
        return Long.parseLong(Constants.DATEFORMAT.format(new Date()));
    }

    /**
     * 验证参数
     *
     * @param paramsMap
     */
    public static void validateParams(Map<String, Object> paramsMap) {
        notNull(paramsMap.get(Constants.APP_ID), String.format("签名验证失败:%s不能为空", Constants.APP_ID));
        notNull(paramsMap.get(Constants.TIMESTAMP), String.format("签名验证失败:%s不能为空", Constants.TIMESTAMP));
        notNull(paramsMap.get(Constants.APP_KEY), String.format("签名验证失败:%s不能为空", Constants.APP_KEY));
        notNull(paramsMap.get(Constants.SIGN), String.format("签名验证失败:%s不能为空", Constants.SIGN));
        notNull(paramsMap.get(Constants.VERSION), String.format("签名验证失败:%s不能为空", Constants.VERSION));
        if (!SignType.contains(paramsMap.get(Constants.SIGN_METHOD).toString())) {
            throw new IllegalArgumentException(String.format("签名验证失败:%s必须为:%s,%s", Constants.SIGN_METHOD, SignType.MD5, SignType.SHA256));
        }
        try {
            Constants.DATEFORMAT.parse(paramsMap.get(Constants.TIMESTAMP).toString());
        } catch (ParseException e) {
            throw new IllegalArgumentException(String.format("签名验证失败:%s格式必须为:%s", Constants.TIMESTAMP, "yyyyMMddHHmmss"));
        }
        String timestamp = paramsMap.get(Constants.TIMESTAMP).toString();
        Long clientTimestamp = Long.parseLong(timestamp);
        //判断时间戳
        if ((getCurrentTimestamp() - clientTimestamp) > Constants.MAX_5_EXPIRE) {
            throw new IllegalArgumentException(String.format("签名验证失败:%s已过期", Constants.TIMESTAMP));
        }
    }

    /**
     * @param paramsMap    必须包含
     * @param clientSecret
     * @return
     */
    public static String validateSign(Map<String, Object> paramsMap, String clientSecret) {
        validateParams(paramsMap);
        paramsMap.remove(Constants.SIGN);
        //重新生成签名
        return getSign(paramsMap, clientSecret);
    }


    /**
     * 得到签名
     *
     * @param paramMap     参数集合不含clientSecret
     *                     必须包含clientId=客户端ID
     *                     signType = SHA256|MD5 签名方式
     *                     timestamp=时间戳
     *                     nonce=随机字符串
     * @param clientSecret 验证接口的clientSecret
     * @return
     */
    public static String getSign(Map<String, Object> paramMap, String clientSecret) {
        if (paramMap == null) {
            return "";
        }
        JSONWriter writer = new JSONWriter(false, false);
        //排序
        Set<String> keySet = paramMap.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        Object signType = paramMap.get(Constants.SIGN_METHOD);
        SignType type = null;
        if (signType != null) {
            type = SignType.valueOf(signType.toString());
        }
        if (type == null) {
            type = SignType.MD5;
        }
        for (String k : keyArray) {
            if (StringUtils.isEmpty(k)) {
                continue;
            }
            if (Constants.APP_KEY.equals(k) || Constants.SIMPLIFY.equals(k)) {
                continue;
            }
            Object value = paramMap.get(k);
            if (value == null) {
                sb.append(k).append("=").append(StringUtils.EMPTY).append("&");
                continue;
            }
            String json = writer.write(value);
            // 参数值为空，则不参与签名
            sb.append(k).append("=").append(json).append("&");
        }
        //暂时不需要个人认证
        sb.append(Constants.APP_KEY + "=").append(writer.write(clientSecret));
        String signStr = "";
        //加密
        switch (type) {
            case MD5:
                signStr = DigestUtils.md5Hex(sb.toString()).toLowerCase();
                break;
            case SHA256:
                signStr = DigestUtils.sha256Hex(sb.toString()).toLowerCase();
                break;
            default:
                break;
        }
        return signStr;
    }


    public enum SignType {
        MD5,
        SHA256;

        public static boolean contains(String type) {
            for (SignType typeEnum : SignType.values()) {
                if (typeEnum.name().equals(type)) {
                    return true;
                }
            }
            return false;
        }
    }
}
